using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace HHHFramework {
    public interface IPool<T> {

       T Allocate();
        bool Recycle(T obj);
    }
    public abstract class Pool<T> : IPool<T>
    {
        /// <summary>
        /// �洢ջ
        /// </summary>
        protected Stack<T> mCacheStack = new Stack<T>();
        protected IObjectFactory<T> mFactory;
        public int CurCount {
            get { return mCacheStack.Count; }
        }

        public T Allocate()
        {
            return mCacheStack.Count > 0 ? mCacheStack.Pop() : mFactory.Create(); 
        }

        public abstract bool Recycle(T obj);
    }

 
    public interface IObjectFactory<T> {
        T Create();
    }
    public class CustomObjectFactory<T> : IObjectFactory<T>
    {
        public CustomObjectFactory(Func<T> factoryMethod) {
            mFactoryMethod = factoryMethod;
        }
        protected Func<T> mFactoryMethod;
        public T Create()
        {
            return mFactoryMethod();
        }
    }

    public class PrefabPool<T> : Pool<T>
    {
        readonly Action<T> mResultMethod;
        public PrefabPool(Func<T> factoryMethod,Action<T> resetMethod=null,int initCount =0) {
            mFactory = new CustomObjectFactory<T>(factoryMethod);
            mResultMethod = resetMethod;
            for (int i = 0; i < initCount; i++)
            {
                mCacheStack.Push(mFactory.Create());
            }
            
        }

        public override bool Recycle(T obj)
        {
            mResultMethod?.Invoke(obj);
            mCacheStack.Push(obj);
            return true;
        }

    }
}

